#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/9/8 22:23
# @Author  : LuChao
# @Site    :
# @Software: PyCharm
import os
import pdfkit
import requests
from bs4 import BeautifulSoup


# 获取python教程小例子的HTML
def get_learn_py_content():
    """
    解析URL，获取需要的html内容
    :return: htmls
    """
    htmls = []

    # 渲染的html模板
    html_template = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="style.css" type="text/css" media="all">
    </head>
    <body>
    {content}
    </body>
    </html>
    """
    for i in range(1,101):
        base_url = 'http://www.runoob.com/python/python-exercise-example' + str(i) + '.html'
        response = requests.get(base_url)
        soup = BeautifulSoup(response.content, 'html.parser')
        # 获取文档内容
        content = soup.find(class_='article-body')
        # 去除图片
        while soup.img:
            soup.img.decompose()
        html = html_template.format(content=content)
        html = html.encode("UTF-8")
        html_name = str(i)+".html"
        with open(html_name, 'wb') as f:
            f.write(html)
        htmls.append(html_name)
    return htmls


def save_pdf(htmls,name):
    """
    把所有html文件转换成pdf文件
    """
    # views视图中可以加上options进行页面布局调试　
    options = {
        'page-size': 'Letter',
        'encoding': "UTF-8",
        'custom-header': [
            ('Accept-Encoding', 'gzip')
        ]
    }

    pdfkit.from_file(htmls, name, options=options)

# 删除.html文件
def del_files(path):
    for root , dirs, files in os.walk(path):
        for name in files:
            if name.endswith(".html"):
                print(name)
                os.remove(os.path.join(root,name))



if __name__=='__main__':
    del_files(os.getcwd())
    save_pdf(get_learn_py_content(),'ptyhon练习100例.pdf')
    del_files(os.getcwd())
